﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MovieCollectionManager.DataModel;
using MovieCollectionManager.Util;

namespace MovieCollectionManager
{
    public partial class ChangePasswordForm : Form
    {
        public ChangePasswordForm()
        {
            InitializeComponent();
        }

        private void ChangePasswordForm_Load(object sender, EventArgs e)
        {
            textBoxUserName.Text = LoginForm.loggedUser;
        }

        private void buttonApplyChange_Click(object sender, EventArgs e)
        {
            using (var db = new MovieCollectionConteiner())
            {
                User user = (from user1 in db.Users
                             where user1.Name == textBoxUserName.Text
                             select user1).First();

                if (!OldPasswordMatches(user.Password))
                {
                    MessageBox.Show("Senhas não conferem!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                user.Password = Security.GenerateHash(textBoxNewPassword.Text);
                db.SaveChanges();
            }

            MessageBox.Show("Usuário atualizado!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            ClearFields();
        }

        private bool OldPasswordMatches(string password)
        {
            string inputOldPassword = Security.GenerateHash(textBoxOldPassword.Text);
            string userOldPassword = password;

            if(inputOldPassword.Equals(userOldPassword)) return true;
            else return false;
        }

        private void ClearFields()
        {
            textBoxOldPassword.Text = "";
            textBoxNewPassword.Text = "";
        }

        private void buttonBack_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
